import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/widget/common_loading_widget.dart';
import 'package:casdon/common/widget/primary_button.dart';
import 'package:casdon/core/utils/page_visibility_mixin.dart';
import 'package:casdon/modules/recipe/application/notification/recipe_favorite_list_notifier.dart';
import 'package:casdon/modules/recipe/data/model/recipe_favorite_model.dart';
import 'package:casdon/modules/recipe/ui/widgets/Recipe_card_item.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class RecipeFavoritesScreen extends ConsumerStatefulWidget {
  final ValueNotifier<bool> refreshNotifier;
  final VoidCallback? onGoExplore;

  const RecipeFavoritesScreen({
    super.key,
    required this.refreshNotifier,
    this.onGoExplore,
  });

  @override
  ConsumerState<RecipeFavoritesScreen> createState() => _RecipeFavoritesState();
}

class _RecipeFavoritesState extends ConsumerState<RecipeFavoritesScreen>
    with PageVisibilityMixin, WidgetsBindingObserver {
  VoidCallback? _refreshListener;
  bool _hasBeenVisible = false;

  @override
  void initState() {
    super.initState();
    _refreshListener = () {
      if (!widget.refreshNotifier.value) return;
      _refreshData();
      widget.refreshNotifier.value = false;
    };
    widget.refreshNotifier.addListener(_refreshListener!);
  }

  @override
  void didUpdateWidget(covariant RecipeFavoritesScreen oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.refreshNotifier != widget.refreshNotifier &&
        _refreshListener != null) {
      oldWidget.refreshNotifier.removeListener(_refreshListener!);
      widget.refreshNotifier.addListener(_refreshListener!);
    }
  }

  @override
  void dispose() {
    if (_refreshListener != null) {
      widget.refreshNotifier.removeListener(_refreshListener!);
    }
    super.dispose();
  }

  @override
  void onPageVisible() {
    if (_hasBeenVisible) {
      _refreshData();
    } else {
      _hasBeenVisible = true;
    }
  }

  void _refreshData() {
    if (mounted == false) return;
    final notifier = ref.read(recipeFavoriteListNotifierProvider.notifier);
    notifier.refresh();
  }

  @override
  Widget build(BuildContext context) {
    final state = ref.watch(recipeFavoriteListNotifierProvider);
    final notifier = ref.watch(recipeFavoriteListNotifierProvider.notifier);
    return buildPageVisibilityDetector(
      context,
      NotificationListener<ScrollNotification>(
        onNotification: (notification) {
          if (notification is ScrollEndNotification &&
              notification.metrics.pixels >=
                  notification.metrics.maxScrollExtent - 50) {
            notifier.loadMore();
          }
          return false;
        },
        child: RefreshIndicator(
          onRefresh: () async {
            notifier.refresh();
          },
          child: CustomScrollView(
            slivers: [
              state.when(
                loading: () => SliverToBoxAdapter(child: _buildLoading()),
                error: (e, _) => SliverToBoxAdapter(child: _buildSliverError()),
                data: (data) {
                  final items = data.data;
                  if (items.isEmpty) {
                    return SliverToBoxAdapter(
                      child: _buildSliverEmpty(context),
                    );
                  }
                  return SliverPadding(
                    padding: EdgeInsets.all(16.w),
                    sliver: SliverGrid(
                      delegate: SliverChildBuilderDelegate((context, index) {
                        final item = items[index];
                        return GestureDetector(
                          onTap: () => {
                            _handleItemClick(item, context),
                          }, // 点击处理
                          child: RecipeCardItem(item: item), // 原有卡片
                        );
                      }, childCount: items.length),
                      gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                        maxCrossAxisExtent: 200.w,
                        mainAxisSpacing: 12.w,
                        crossAxisSpacing: 12.w,
                        mainAxisExtent: 144.h,
                      ),
                    ),
                  );
                },
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildLoading() => const Padding(
    padding: EdgeInsets.symmetric(vertical: 40),
    child: Center(child: CommonLoadingWidget()),
  );

  Widget _buildSliverError() {
    return _buildSliverEmpty(context);
  }

  Widget _buildSliverEmpty(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(top: 102.h),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Image.asset(Assets.images.emptyData.path, width: 120.w, height: 80.h),
          SizedBox(height: 12.h),
          Text('还没有收藏任何菜谱哦', style: TextStyle(color: Colors.grey.shade500)),
          SizedBox(height: 16.h),
          PrimaryButton(
            text: '去看菜谱',
            textStyle: context.textTheme.bodyMedium?.copyWith(
              color: Colors.white,
            ),
            width: 100.w,
            height: 32.h,
            onPressed: widget.onGoExplore,
          ),
        ],
      ),
    );
  }

  _handleItemClick(RecipeFavoriteModel item, BuildContext context) {
    RecipeDetailRoute(
      recipeId: item.recipeId,
      title: item.title,
      isSmart: item.isSmart,
    ).push(context);
  }
}
